<?php

namespace common\rewrites;

use wbraganca\dynamicform\DynamicFormAsset;
use yii\base\InvalidConfigException;
use yii\web\View;

class DynamicFormWidget extends \wbraganca\dynamicform\DynamicFormWidget
{
    public $jqOnId;

    /**
     * Registers the needed assets.
     *
     * @param View $view The View object
     */
    public function registerAssets($view)
    {
        DynamicFormAsset::register($view);
        // add a click handler for the clone button
        $js1 = 'jQuery("#' . ($this->jqOnId?:$this->formId) . '").on("click", "' . $this->insertButton . '", function(e) {'. "\n";
        $js1 .= "    e.preventDefault();\n";
        $js1 .= '    jQuery(".' .  $this->widgetContainer . '").triggerHandler("beforeInsert", [jQuery(this)]);' . "\n";
        $js1 .= '    jQuery(".' .  $this->widgetContainer . '").yiiDynamicForm("addItem", '. $this->getHashVarName() . ", e, jQuery(this));\n";
        $js1 .= "});\n";
        // add a click handler for the remove button
        $js1 .= 'jQuery("#' . ($this->jqOnId?:$this->formId) . '").on("click", "' . $this->deleteButton . '", function(e) {'. "\n";
        $js1 .= "    e.preventDefault();\n";
        $js1 .= '    jQuery(".' .  $this->widgetContainer . '").yiiDynamicForm("deleteItem", '. $this->getHashVarName() . ", e, jQuery(this));\n";
        $js1 .= "});\n";
        if ($this->jqOnId) {
            $jsFunName = "DynamicWidgetId{$this->id}";
$js0 = <<<JS
if (typeof($jsFunName) === "undefined") {
    var $jsFunName = function () {
        $js1
    }
    $jsFunName();
}
JS;
            $view->registerJs($js0, $view::POS_END);
        } else {
            $view->registerJs($js1, $view::POS_END);
        }
        $js2 = 'jQuery("#' . $this->formId . '").yiiDynamicForm(' . $this->getHashVarName() .');' . "\n";
        $view->registerJs($js2, $view::POS_LOAD);
    }
}